package topoSort;
import java.awt.Point;
import java.util.ArrayList;
import java.util.Random;
import java.util.Vector;

import javafx.util.Pair;

public class GraphGenerator {
	
	/**
	 * Generate graph in model with n vertices and m edges 
	 * implements bubble layout with vertices on scene
	 * @param model
	 * @param scene
	 * @param n
	 * @param m
	 */
	public static void generate(Model model, Scene scene, Integer n, Integer m) {
		Random rand = new Random(System.currentTimeMillis());
			
		final int radius = 200;
		final int offsetX = 500;
		final int offsetY = 300;
		scene.clear();
		model.clear();

		// TODO Optimize to lock model for better performance on scene
		for (int i = 0; i < n; ++i) {
			model.addVertex();
		}

		ArrayList<Integer> ids = new ArrayList<Integer>(model.getVeticesIds());

		float delta = (float) (2 * Math.PI / (float) (n));
		for (int i = 0; i < n; i++) {
			int x = (int) (Math.cos(delta * i) * radius + offsetX);
			int y = (int) (Math.sin(delta * i) * radius + offsetY);
			scene.setVertexPos(ids.get(i), new Point(x, y));
		}

		// TODO Update algorithm to list possible edges
		// and choose from them some random ones
		ids = new ArrayList<Integer>(model.getVeticesIds());
		Vector<Pair<Integer, Integer>> ll = new Vector<Pair<Integer, Integer>>();
		for (int i = 0; i < n; i++)
		{
			for (int j = i + 1; j < n; j++)
			{
				ll.add(new Pair<Integer, Integer>(i, j));
			}
		}
		
		for (int i = 0; i < m; i++)
		{
			int z = rand.nextInt(ll.size());
			if(rand.nextBoolean())
			{
				model.addLink(ll.get(z).getKey(), ll.get(z).getValue());
			}
			else
			{
				model.addLink(ll.get(z).getValue(), ll.get(z).getKey());
			}
			ll.remove(z);
		}
		
		model.sort();
	}
}
